package com.wang.experiment.experiment3.booksystem;

import javax.swing.*;
import java.awt.*;

/**
 * @author wr
 * @date 2021/10/26 20:38
 */
public class DeleteBookDialog extends JDialog {
    private final BookSystem bookSystem;
    private final BookManager manager;

    public DeleteBookDialog(BookSystem bookSystem, BookManager manager) {
        super(bookSystem, "删除书籍", true);
        this.bookSystem = bookSystem;
        this.manager = manager;
        init();
    }

    private void init() {
        Rectangle parentBounds = getParent().getBounds();
        setBounds(parentBounds.x + parentBounds.width / 4,
                parentBounds.y + parentBounds.height / 4,
                parentBounds.width / 2,
                parentBounds.height / 2);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLayout(new BorderLayout());

        //init input
        JPanel bookIdPanel = new JPanel(new FlowLayout());
        JLabel bookId = new JLabel("书籍id:");
        JTextField bookIdInput = new JTextField(16);
        bookIdPanel.add(bookId);
        bookIdPanel.add(bookIdInput);
        add(bookIdPanel, BorderLayout.CENTER);

        //init btn
        JPanel btnPanel = new JPanel(new FlowLayout());
        JButton deleteBtn = new JButton("删除");
        deleteBtn.addActionListener(e -> {
            Book book = manager.getBookById(bookIdInput.getText());
            if(book == null){
                JOptionPane.showMessageDialog(this, "不存在该书籍id", "警告", JOptionPane.WARNING_MESSAGE);
            }else {
                int result = JOptionPane.showConfirmDialog(bookSystem, "确认删除?", "删除", JOptionPane.YES_NO_OPTION);
                if(result == JOptionPane.YES_OPTION){
                    manager.deleteBook(book.getId());
                    //刷新书籍列表
                    bookSystem.showBookData(manager.getBookList());
                    dispose();
                }
            }
        });
        btnPanel.add(deleteBtn);
        add(btnPanel, BorderLayout.SOUTH);

        setVisible(true);
    }
}
